package org.fjsei.yewu.controller;

import com.querydsl.core.BooleanBuilder;
import md.cm.base.*;
import md.cm.unit.Unit;
import md.cm.unit.Units;
import md.specialEqp.Eqp;
import md.specialEqp.Equipment;
import md.specialEqp.Equipments;
//import md.specialEqp.QEqp;
import md.specialEqp.inspect.*;
import md.specialEqp.type.PipingUnit;
//import md.specialEqp.type.QPipingUnit;
import md.system.User;
import md.system.UserRepository;
import org.fjsei.yewu.entity.sdn.TestBean;
import org.fjsei.yewu.jpa.PageOffsetFirst;
import org.fjsei.yewu.service.core.RestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import jakarta.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static org.springframework.transaction.annotation.Propagation.REQUIRES_NEW;

@RestController
public class Api {
    @Autowired
    private RestService restService;
    @Resource
    private Units units;
    @Resource  private Companies companies;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private Persons persons;
    @Autowired
    private Equipments eQPRepository;
    @Autowired
    private IspRepository ispRepository;
    @Autowired
    private DetailRepository detailRepository;
    /**CountAll会等待当前他人的Unit.Insert事务结束才能返回！ 等待时间可能很长的。
     * */
    @PreAuthorize("hasAnyRole('JyUser','Master')")
    @GetMapping("/")
    @Transactional(readOnly = true)
    public String hello(){
        Long allunit= units.count();
        return "hello 测试 Unit table Count="+allunit;
    }
    /**读取特定Id一条的不会阻塞于其它Unit.Insert事务。
     *加不加 @Transactional(readOnly = true) 实际效果一样的。
    * */
    @GetMapping("/unitID")
    @Transactional(readOnly = false)
    public String helloUnitId(){
        UUID id=UUID.fromString("00001515-f1cd-4aff-936c-409a34dcf8f3");
        Person person= persons.findByName("何尔章");
        Pageable pageable= PageOffsetFirst.of(0, 10);
        QIsp qm = QIsp.isp;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qm.id.eq(id));
        Slice<Isp> rpage= (Slice<Isp>)ispRepository.findAll(builder,pageable);
        Isp isp=rpage.getContent().get(0);
        UUID id2=UUID.fromString("6a8f0ccd-f591-4682-b54a-770277abd0a7");
        //Unit eqp=units.getReferenceById(id2);
        Unit unit=isp.getServu();
        //isp.setIspu(eqp);
        Company company=unit.getCompany();
        company.setName(company.getName()+"_es78odE");
//        User user=userRepository.findByUsername("herzhang");
        //eqp.setVart("672");      //"671"
        companies.save(company);
        return "hello 测试 Eqp HS change="+isp.getId();
    }
    /**根据Company.Name来关联搜索的，就会阻塞于其它Company.Insert事务。 运行受阻了反应慢。
     * #等待时间可能很长的! 只能指望所有大部分的事务都应该在非常短暂时间内就能提交，不可长时间停留在CRDB小强数据库事务之内。或者拆解独立的小小事务。
     * */
    @GetMapping("/unitName")
    public String helloUnitName(){
        Unit unit= units.findUnitByCompany_Name("福建省晋江粉末冶金制品厂");
        return "hello 测试 unit name to ID="+unit.getCompany().getId();
    }
    /** 没有索引的字段匹配查询：
     * */
    @GetMapping("/unitNo")
    public String helloUnitNo(){
        Unit unit= units.findUnitByCompany_No("9135012161133267XU");
        return "hello 测试 unit No to Name="+unit.getCompany().getName();
    }

    @GetMapping("/CompanyGetAll")
    public String allCompanyName(){
        System.out.println("CompanyGetAll开动");
        List<Company>  companies= this.companies.findAll();
        System.out.println("CompanyGetAll最后");
        return "CompanyGetAll测试 count="+companies.size();
    }

    @PostMapping("/CompanyInsert")
    @Transactional(propagation = REQUIRES_NEW)
    public TestBean setEnumComp(@RequestBody TestBean testBean){
        System.out.println("CompanyInsert开动");
        Company company=new Company();
        company.setName(testBean.getXxxx());
        company.setNo(testBean.getFramwork()+testBean.getXxxx());
        company.setAddress("测试用等待测试后删除Api");
        try {
            Thread.sleep(12*1000);   //模拟事务耗时
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        companies.save(company);
        System.out.println("CompanyInsert最后随后事务真的commit");
        return testBean;
    }

    /*
     * {
     *     "framwork":"SPRINGDATA",
	 *     "xxxx":"干扰用"
     *  }
     */
    @PostMapping("/enum")
    public TestBean getEnum(@RequestBody TestBean testBean){
        System.out.println(testBean.toString());
        return testBean;
    }

    //注意：　/test/   和 /test 是两个不同的URL
    //因为application.yml文件加servlet.context-path: /file/v1 其引用upload-URI: ${server.servlet.context-path}/upload/ 导致端点变成了 http://192.168.3.245:8673/file/v1/test/
    @GetMapping("/test/")
    public String findEQPByName(){
    //        Eqp eqp=restService.findByName("电梯AT032039");
    //        中文为啥不行？乱码啊，
        return "base api access? test,if frontend cannot use!"; //"前端没法登录的，后端直接接口测试，原始基础测试";
    }
    @RequestMapping("/test/{name}")
    public String findEQPByName(@PathVariable String name) {
        Eqp eqp=restService.findByName(name);
        return eqp!=null?eqp.toString():"没找到";
    }
}


//stream三点特性.stream不存储数据.stream不改变源数据.stream延迟执行特性; https://www.cnblogs.com/andywithu/p/7404101.html
